<?php

namespace houze;

/**
 * Cookie缓存
 */
class Cookie
{
    /**
     * 是否存在
    */
    public static function has($key) {
        $Request = \houze\context\Request::get();
        $key = \houze\Config::get('app.cookies_prefix').$key;
        if (isset($Request->cookie[$key])) return true;
        
        return false;
    }
    
    /**
     * 读取
    */
    public static function get($key) {
        $Request = \houze\context\Request::get();
        $key = \houze\Config::get('app.cookies_prefix').$key;
        if (isset($Request->cookie[$key]) == false) return false;
        return $Request->cookie[$key];
    }

    /**
     * 写入
    */
    public static function set($key,$val,$time=null) {
        $config = \houze\Config::get('app');
        $key = $config['cookies_prefix'].$key;
        if (empty($time)) {
            $time = $config['cookies_outtime'];
        }
        $time += time();
        $Response = \houze\context\Response::get();
        return $Response->cookie($key, $val, $time, $config['cookies_path'], $config['cookies_domain'], $config['cookies_secure'], $config['cookies_httponly']);
    }

    /**
     * 删除
    */
    public static function delete($key) {
        $config = \houze\Config::get('app');
        $key = $config['cookies_prefix'].$key;
              
        $Request = \houze\context\Request::get();
        $Response = \houze\context\Response::get();
        if (isset($Request->cookie[$key]) == false) return false;
        
        return $Response->cookie($key, null, -1, $config['cookies_path'], $config['cookies_domain'], $config['cookies_secure'], $config['cookies_httponly']);
    }

    /**
     * 清空
    */
    public static function clear() {
        $config = \houze\Config::get('app');
        $Request = \houze\context\Request::get();
        $Response = \houze\context\Response::get();

        if (isset($Request->cookie) == false) return false;

        foreach ($Request->cookie as $key=>$val) {
            $Response->cookie($key, null, -1, $config['cookies_path'], $config['cookies_domain'], $config['cookies_secure'], $config['cookies_httponly']);
        }
        
        return true;
    }
    
}